#pragma once
#include <iostream>
#include <memory>
#include "connection.hpp"
#include "HandlerConnection.hpp"
#include "Log.hpp"
#include "Reactor.hpp"
#include "Common.hpp"
#include <error.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/epoll.h>

// 连接管理器
class Accepter
{
public:
    // EL模式下有多个连接怎么处理，一次读多个连接
    static void AccepterConnection(Connection::ptr conn)
    {
        errno = 0;
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int newsockfd = accept(conn->SockFd(), (struct sockaddr *)&peer, &len);
            if (newsockfd > 0)
            {
                lg(Info, "get is new link fd : %d", newsockfd);
                //先设置fd的非阻塞
                SetNonBlock(newsockfd);
                // 创建连接
                Connection::ptr normal_conn = std::make_shared<Connection>(newsockfd, EPOLLIN | EPOLLET, conn->_R);
                //注册io方法
                normal_conn->RegisterCallback(HandlerConnection::Reader, HandlerConnection::Sender, HandlerConnection::Excepter);
                normal_conn->SetAddr(peer);           // 维护客户端信息
                conn->_R->AddConnection(normal_conn); // 维护新链接
            }
            else
            {
                if (errno == EAGAIN)
                    break; // 底层数据被读完
                else if (errno == EINTR)
                    continue; // 信号中断
                else
                {
                    lg(Error, "get is new link error");
                    return;
                }
            }
        }
    }
};